<?php

namespace app\store\controller;

use app\store\model\Goods as GoodsModel;
use app\store\model\Category as CategoryModel;
use app\store\service\Goods as GoodsService;
use app\common\model\GoodsDoctorComment;
/**
 * 商品管理控制器
 * Class Goods
 * @package app\store\controller
 */
class Goods extends Controller
{
    /**
     * 商品列表(出售中)
     * @return mixed
     * @throws \think\exception\DbException
     */
    public function index()
    {
        // 获取全部商品列表
        $model = new GoodsModel;
        $list = $model->getList(array_merge(['status' => -1], $this->request->param()));
        
        // 商品分类
        $catgory = CategoryModel::getCacheTree();
        // dump($catgory);die;
        return $this->fetch('index', compact('list', 'catgory'));
    }
    /**
     * 排班
     *
     * Undocumented function long description
     *
     * @param Type $var Description
     * @return type
     * @throws conditon
     **/
    public function editpaiban()
    {
        if (!$this->request->isPost()) {
            $goods_id = input('goods_id');
    
            // 查询当前医生的每周排班情况
            $paiban = DB('goods_weekly_schedule')
                ->where('goods_id', $goods_id)
                ->select();
    
            $goods = DB("goods")->where("goods_id", $goods_id)->find();
            $cat = DB("category")->where("category_id", $goods['category_id'])->find();
    
            return $this->fetch('paiban', compact('goods_id', 'paiban', 'goods', 'cat'));
        }
    }
    public function getPaibanData()
    {
        $goods_id = input('goods_id');
        $month = input('month');
        $startOfMonth = date("Y-m-01", strtotime($month));
        $endOfMonth = date("Y-m-t", strtotime($month));

        $paiban = DB('goods_paiban')
            ->where('goods_id', $goods_id)
            ->whereBetween('day', [$startOfMonth, $endOfMonth])
            ->select();

        return json(['paiban' => $paiban]);
    }
    /**
     * 添加商品
     * @return array|mixed
     * @throws \think\exception\PDOException
     */
    public function add()
    {
        if (!$this->request->isAjax()) {
            return $this->fetch(
                'add',
                array_merge(GoodsService::getEditData(null, 'add'), [])
            );
        }
        $model = new GoodsModel;
        // dump($this->postData('goods')['category_id']);die;
        // 开始判断医生科室分类   如果是一级分类  不让其添加
        if (DB("category")->where("category_id",$this->postData('goods')['category_id'])->find()['parent_id'] == 0) {
            return $this->renderError('必须选择二级科室');
        }
        // dump($this->postData('goods'));die;
        if ($model->add($this->postData('goods'))) {
            return $this->renderSuccess('添加成功', url('goods/index'));
        }
        return $this->renderError($model->getError() ?: '添加失败');
    }

    

    /**
     * 商品编辑
     * @param $goods_id
     * @return array|bool|mixed
     */
    public function edit($goods_id)
    {
        // 商品详情
        $model = GoodsModel::detail($goods_id);
        if (!$this->request->isAjax()) {
            return $this->fetch(
                'edit',
                array_merge(GoodsService::getEditData($model), compact('model'))
            );
        }
        if (DB("category")->where("category_id",$this->postData('goods')['category_id'])->find()['parent_id'] == 0) {
            return $this->renderError('必须选择二级科室');
        }
        // 更新记录
        if ($model->edit($this->postData('goods'))) {
            return $this->renderSuccess('更新成功', url('goods/index'));
        }
        return $this->renderError($model->getError() ?: '更新失败');
    }

    /**
     * 修改商品状态
     * @param $goods_id
     * @param boolean $state
     * @return array
     */
    public function state($goods_id, $state)
    {
        // 商品详情
        $model = GoodsModel::detail($goods_id);
        if (!$model->setStatus($state)) {
            return $this->renderError('操作失败');
        }
        return $this->renderSuccess('操作成功');
    }

    /**
     * 删除商品
     * @param $goods_id
     * @return array
     */
    public function delete($goods_id)
    {
        // 商品详情
        $model = GoodsModel::detail($goods_id);
        if (!$model->setDelete()) {
            return $this->renderError($model->getError() ?: '删除失败');
        }
        return $this->renderSuccess('删除成功');
    }
    // 新的排班
    // public function getWeeklySchedule()
    // {
    //     $goods_id = input('goods_id');
    //     $schedules = Db('goods_weekly_schedule')
    //         ->where('goods_id', $goods_id)
    //         ->order('week_day')
    //         ->select();
    //         $goods  = DB("goods")->where("goods_id",$goods_id)->find();   
    //         $cat = DB("category")->where("category_id",$goods['category_id'])->find();
    //     return json(['schedule' => $schedules]);
    // }
    public function getWeeklySchedule()
    {
        $goods_id = input('goods_id');

        // 查询排班
        $schedules = Db('goods_weekly_schedule')
            ->where('goods_id', $goods_id)
            ->order('week_day')
            ->select();

        // 查询号源规则
        $rules = Db('doctor_schedule_source_rule')
            ->where('doctor_id', $goods_id)
            ->select();

        // 医生信息（可选）
        $goods  = Db("goods")->where("goods_id", $goods_id)->find();   
        $cat = Db("category")->where("category_id", $goods['category_id'])->find();

        return json([
            'schedule' => $schedules,
            'source_rules' => $rules,
            'goods' => $goods,
            'cat' => $cat
        ]);
    }
    // public function editWeeklySchedule()
    // {
    //     // 获取请求数据
    //     $data = request()->post();
    //     $goods_id = input('goods_id');
    
    //     // 检查医生ID是否为空
    //     if (empty($goods_id)) {
    //         return $this->renderError('医生ID不能为空');
    //     }
    
    //     // **检查数据格式是否正确**
    //     if (!isset($data['schedule']) || !is_array($data['schedule'])) {
    //         return $this->renderError('提交的排班数据格式错误');
    //     }
    
    //     // 清空该医生的所有排班记录
    //     DB('goods_weekly_schedule')->where('goods_id', $goods_id)->delete();
    
    //     // 处理排班数据
    //     $record = [];
    //     foreach ($data['schedule'] as $item) {
    //         // 确保 `week_day` 存在且有效
    //         if (!isset($item['week_day']) || !is_numeric($item['week_day'])) {
    //             return $this->renderError('数据格式错误：缺少 week_day');
    //         }
    
    //         $record[] = [
    //             'goods_id' => $goods_id,
    //             'week_day' => $item['week_day'],
    //             'morning' => !empty($item['morning']) ? 1 : 0,
    //             'afternoon' => !empty($item['afternoon']) ? 1 : 0,
    //             'night' => !empty($item['night']) ? 1 : 0,
    //             'create_time' => time(),
    //             'update_time' => time(),
    //         ];
    //     }
    
    //     // **检查是否有数据**
    //     if (empty($record)) {
    //         return $this->renderError('未提供有效的排班数据');
    //     }
    
    //     // 插入数据到数据库
    //     $result = DB('goods_weekly_schedule')->insertAll($record);
    //     // return $this->renderSuccess('添加成功', url('goods/index'),[]);
    //     // return $this->renderSuccess('提交成功', url('goods/index'));
    //     // return $this->renderSuccess();
    // }
    public function editWeeklySchedule()
    {
        $data = request()->post();
        $goods_id = input('goods_id');
        if (empty($goods_id)) {
            return $this->renderError('医生ID不能为空');
        }

        if (!isset($data['schedule']) || !is_array($data['schedule'])) {
            return $this->renderError('提交的排班数据格式错误');
        }

        // 清空旧排班数据
        DB('goods_weekly_schedule')->where('goods_id', $goods_id)->delete();
        // 清空旧号源规则数据
        DB('doctor_schedule_source_rule')->where('doctor_id', $goods_id)->delete();

        $record = [];       // 排班记录
        $sourceRules = [];  // 号源规则记录

        foreach ($data['schedule'] as $item) {
            if (!isset($item['week_day'])) continue;
            $week_day = $item['week_day'];

            $row = [
                'goods_id' => $goods_id,
                'week_day' => $week_day,
                'morning' => isset($item['morning']['enabled']) && $item['morning']['enabled'] ? 1 : 0,
                'afternoon' => isset($item['afternoon']['enabled']) && $item['afternoon']['enabled'] ? 1 : 0,
                'night' => isset($item['night']['enabled']) && $item['night']['enabled'] ? 1 : 0,
                'create_time' => time(),
                'update_time' => time(),
            ];
            $record[] = $row;

            // 添加每个时间段的号源规则
            foreach (['morning', 'afternoon', 'night'] as $section) {
                if (!isset($item[$section]) || empty($item[$section]['enabled'])) continue;

                    $mode      = $item[$section]['mode'];
                    $fixedNum  = $mode === 'fixed'  ? intval($item[$section]['fixed_num'])  : null;
                    $randomMin = $mode === 'random' ? intval($item[$section]['random_min']) : null;
                    $randomMax = $mode === 'random' ? intval($item[$section]['random_max']) : null;

                    $sourceRules[] = [
                        'doctor_id'   => $goods_id,
                        'week_day'    => $week_day,
                        'section'     => $section,
                        'mode'        => $mode,
                        'fixed_num'   => $fixedNum,
                        'random_min'  => $randomMin,
                        'random_max'  => $randomMax,
                        'is_enabled'  => 1,
                        'create_time' => date('Y-m-d H:i:s'),
                        'update_time' => date('Y-m-d H:i:s'),
                    ];

                    // ★ 同步到 yoshop_goods_weekly_schedule
                    // $this->syncScheduleRemain(
                    //     $goods_id, $week_day, $section, $mode, $fixedNum, $randomMin, $randomMax
                    // );
            }
        }
        if (!empty($record)) {
            DB('goods_weekly_schedule')->insertAll($record);
        }
        // ★ 统一同步（只更新不插入，避免重复行）
        $this->applyScheduleToRemain($goods_id, $data['schedule']);
        if (!empty($sourceRules)) {
            DB('doctor_schedule_source_rule')->insertAll($sourceRules);
        }

        // return $this->renderSuccess('排班与号源设置已保存');
    }
    /**
     * 同步 goods_weekly_schedule：把每次排班对应的剩余号数/初始号数写入
     *
     * @param int    $goods_id
     * @param int    $week_day       1-7
     * @param string $section        morning|afternoon|night
     * @param string $mode           fixed|random
     * @param int    $fixed_num      固定数量（mode=fixed）
     * @param int    $random_min     随机最小（mode=random）
     * @param int    $random_max     随机最大（mode=random）
     */
    private function syncScheduleRemain($goods_id, $week_day, $section, $mode, $fixed_num = null, $random_min = null, $random_max = null)
    {
        // 计算应写入的号数
        if ($mode === 'fixed') {
            $val = max(0, (int)$fixed_num);
        } else {
            $min = max(0, (int)$random_min);
            $max = max($min, (int)$random_max);
            $val = mt_rand($min, $max);
        }

        // 字段映射（按你的表结构）
        $flagColMap = [
            'morning'   => 'morning',
            'afternoon' => 'afternoon',
            'night'     => 'night',
        ];
        $numColMap = [
            'morning'   => 'morning_num',
            'afternoon' => 'afternoon_num',
            'night'     => 'night_num',
        ];
        $initColMap = [
            'morning'   => 'morning_init_num',
            'afternoon' => 'afternoon_init_num',
            'night'     => 'night_init_num',
        ];

        if (!isset($flagColMap[$section])) {
            // 不合法的 section，直接返回
            return;
        }

        $flagCol = $flagColMap[$section];
        $numCol  = $numColMap[$section];
        $initCol = $initColMap[$section];

        $where = ['goods_id' => (int)$goods_id, 'week_day' => (int)$week_day];
        $now   = time();

        // 查询是否已有该医生该星期的行
        $row = \think\Db::name('goods_weekly_schedule')->where($where)->find();

        if (!$row) {
            // 没有则插入一条基础行（其他时段默认 0 / 10 可按需调整）
            $insert = array_merge($where, [
                // 出诊开关：本时段置 1，其它保持 0
                'morning'  => $section === 'morning'   ? 1 : 0,
                'afternoon'=> $section === 'afternoon' ? 1 : 0,
                'night'    => $section === 'night'     ? 1 : 0,

                // 先给默认值，然后覆盖本时段
                'morning_num'        => 10,
                'afternoon_num'      => 10,
                'night_num'          => 10,
                'morning_init_num'   => 10,
                'afternoon_init_num' => 10,
                'night_init_num'     => 10,

                'create_time' => $now,
                'update_time' => $now,
            ]);

            // 覆盖本时段的 init 与 num 为计算值
            $insert[$numCol]  = $val;
            $insert[$initCol] = $val;

            \think\Db::name('goods_weekly_schedule')->insert($insert);
        } else {
            // 已有则更新本时段的开关 + init + num
            $update = [
                $flagCol    => 1,
                $numCol     => $val,
                $initCol    => $val,
                'update_time' => $now,
            ];

            \think\Db::name('goods_weekly_schedule')->where($where)->update($update);
        }
    }
    /**
     * 将保存的每周排班，同步到 yoshop_goods_weekly_schedule
     * —— 只做 UPDATE，不做 INSERT（避免与 insertAll 冲突）
     *
     * @param int   $goods_id
     * @param array $schedule  结构同前端提交的 schedule
     */
    private function applyScheduleToRemain($goods_id, array $schedule)
    {
        $now = time();

        foreach ($schedule as $item) {
            if (empty($item['week_day'])) continue;
            $week_day = (int)$item['week_day'];

            $upd = ['update_time' => $now];

            foreach (['morning','afternoon','night'] as $sec) {
                $enabled = !empty($item[$sec]['enabled']);
                $upd[$sec] = $enabled ? 1 : 0;   // 开关

                $numCol  = $sec . '_num';
                $initCol = $sec . '_init_num';

                if ($enabled) {
                    $mode = $item[$sec]['mode'] ?? 'fixed';
                    if ($mode === 'fixed') {
                        $val = max(0, (int)($item[$sec]['fixed_num'] ?? 0));
                    } else {
                        $min = max(0, (int)($item[$sec]['random_min'] ?? 0));
                        $max = max($min, (int)($item[$sec]['random_max'] ?? $min));
                        $val = mt_rand($min, $max);
                    }
                } else {
                    // 未启用时可按你的业务设为 0（避免残留默认 10）
                    $val = 0;
                }

                $upd[$numCol]  = $val;
                $upd[$initCol] = $val;
            }

            \think\Db::name('goods_weekly_schedule')
                ->where(['goods_id' => (int)$goods_id, 'week_day' => $week_day])
                ->update($upd);
        }
    }
    public function deleteWeeklySchedule()
    {
        $id = request()->post('id');
        if (empty($id)) {
            return $this->renderError('ID 不能为空');
        }

        $result = DB('goods_weekly_schedule')->where('id', $id)->delete();
        return $result ? $this->renderSuccess('删除成功') : $this->renderError('删除失败');
    }
    /**
     * undocumented function summary
     *
     * Undocumented function long description
     *
     * @param Type $var Description
     * @return type
     * @throws conditon
     **/
    public function comment()
    {
        // 获取全部商品列表
        $model = new GoodsDoctorComment;
        $list = $model->getList(array_merge(['status' => -1], $this->request->param()));
        // dump($list);    die;
        // 商品分类
        $catgory = CategoryModel::getCacheTree();
        return $this->fetch('comment', compact('list','catgory'));
    }
    /**
     * undocumented function summary
     *
     * Undocumented function long description
     *
     * @param Type $var Description
     * @return type
     * @throws conditon
     **/
    public function comment_delete()
    {
        $comment_id = input('comment_id');
        if (!DB("goods_doctor_comment")->where("comment_id",$comment_id)->delete()) {
            return $this->renderError('删除失败');
        }
        return $this->renderSuccess('删除成功');
    }
    public function toggle_show()
    {
        $commentId = input('comment_id/d');
        $isShow = input('is_show/d', 1);

        if (!$commentId) {
            return $this->renderError('缺少参数');
        }

        $comment = GoodsDoctorComment::get($commentId);
        if (!$comment) {
            return $this->renderError('评价不存在');
        }

        $comment->is_show = $isShow;
        if ($comment->save()) {
            return $this->renderSuccess([], '操作成功');
        } else {
            return $this->renderError('操作失败');
        }
    }
    // 切换是否专题展示
    public function toggleZtShow()
    {
        $goodsId = input('goods_id/d');
        $isZtShow = input('is_zt_show/d', 0);

        if (!$goodsId) {
            return $this->renderError('参数错误');
        }
        $model = GoodsModel::detail($goodsId);
        // dump($model);die;
        if (!$model) {
            return $this->renderError('医生不存在');
        }
        unset($model['goods_image']); // 如果你有拼接这个字段
        unset($model['goods_sku']); // 如果你有拼接这个字段
        $model->save(['is_zt_show' => $isZtShow]);

        return $this->renderSuccess('操作成功');
    }
}
